package com.atguigu.gulimall.search.thread;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Data time:2022/4/4 16:53
 * StudentID:2019112118
 * Author:hgw
 * Description: 测试初始化线程的4种方式
 */
public class ThreadTest {
    // 当前系统池只有一两个，每个异步任务直接提交给线程池，让他自己去执行
    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("main...start....");
/*
        CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
            System.out.println("当前线程: " + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果：" + i);
        }, executor);*/

        /**
         * 方法完成之后的感知
         */
/*        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程: " + Thread.currentThread().getId());
            int i = 10 / 0;
            System.out.println("运行结果：" + i);
            return i;
        }, executor).whenComplete((result,exception)->{
            // 虽然能得到异常信息，但是没法修改返回数据
            System.out.println("异步任务成功完成了...结果是：" + result+";异常是："+exception);
        }).exceptionally(throwable -> {
            // 可以感知异常同时返回指定默认值
            System.out.println(throwable);
            return 10;
        });*/

        /**
         * 方法执行完成后的处理
         */
        /*CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程: " + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果：" + i);
            return i;
        }, executor).handle((res,thr)->{
            if (res != null) {
                return res *2;
            }
            if (thr != null) {
                return 0;
            }
            return 0;
        });*/

        /**
         * 线程串行化
         *  1)、thrnRun ：不能获取到上一步的执行结果，并无返回值
         *  2)、thenAccept : 能接收上一步结果，但是无返回值
         *  3)、thenApply ：能接收上一步结果，并有返回值
         */
        /*CompletableFuture<Void> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程1: " + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果：" + i);
            return i;
        }, executor).thenRunAsync(() -> {
            System.out.println("任务2启动了...");
        }, executor);

        CompletableFuture<Void> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程2: " + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果：" + i);
            return i;
        }, executor).thenAcceptAsync(res->{
            System.out.println("任务2启动了..." + res);
        },executor);

        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程2: " + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果：" + i);
            return i;
        }, executor).thenApplyAsync(res -> {
            System.out.println("任务2启动了..." + res);
            return "Hello" + res;
        }, executor);
        System.out.println("返回值:"+future.get());*/

        /**
         * 两个异步任务都完成
         */
        /*CompletableFuture<Integer> future01 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务1线程: " + Thread.currentThread().getId());
            int i = 10 / 4;
            System.out.println("任务1结束");
            return i;
        }, executor);
        CompletableFuture<String> future02 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务2线程: " + Thread.currentThread().getId());
            System.out.println("任务2结束");
            return "Hello";
        }, executor);

        future01.runAfterBothAsync(future02, ()->{
            System.out.println("任务3开始...");
        },executor);

        future01.thenAcceptBothAsync(future02, (f1,f2)->{
            System.out.println("任务3开始,之前的结果：f1="+f1+";f2="+f2);
        },executor);

        CompletableFuture<String> future = future01.thenCombineAsync(future02, (f1, f2) -> {
            return f1 + ":" +f2 +"->HaHa";
        }, executor);
        System.out.println("方法3的返回结果:" + future.get());*/


        /**
         * 两个异步任务只要有一个完成，我们就执行任务3
         *  runAfterEither： 不感知结果，自己也没有返回值
         *  acceptEither ： 感知结果，自己没有返回值
         */
        /*CompletableFuture<Object> future01 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务1线程: " + Thread.currentThread().getId());
            int i = 10 / 4;
            System.out.println("任务1结束");
            return i;
        }, executor);
        CompletableFuture<Object> future02 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务2线程: " + Thread.currentThread().getId());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("任务2结束");
            return "Hello";
        }, executor);

//        CompletableFuture<Void> future3 = future01.runAfterEitherAsync(future02, () -> {
//            System.out.println("任务3开始...");
//        }, executor);
//        CompletableFuture<Void> future4 = future01.acceptEitherAsync(future02, (res) -> {
//            System.out.println("任务3开始..." + res);
//        }, executor);
        CompletableFuture<String> future = future01.applyToEitherAsync(future02, res -> {
            System.out.println("任务3开始..." + res);
            return res.toString() + "-->haha";
        }, executor);*/

        CompletableFuture<String> futureImg = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("查询商品图片信息");
            return "hllo.jpg";
        }, executor);
        CompletableFuture<String> futureAttr = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("查询商品的属性");
            return "星空白+256G";
        }, executor);
        CompletableFuture<String> futureDesc = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("查询商品的介绍");
            return "苹果";
        }, executor);
        CompletableFuture<Object> anyOf = CompletableFuture.anyOf(futureImg, futureAttr, futureDesc);
        anyOf.get();

        /*CompletableFuture<Void> allOf = CompletableFuture.allOf(futureImg, futureAttr, futureDesc);
        allOf.get();    // 等待所有结果完成*/

        System.out.println("main...end...." );
    }




    public void Thread01(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("main...start....");
        /**
         * 1. 继承 Thread
         *      Thread01 thread = new Thread01();
         *      thread.start();
         * 2. 实现 Runnable 接口
         *      Runable01 runable01 = new Runable01();
         *      new Thread(runable01).start();
         * 3. 实现 Callable接口 + FutureTask （可以拿到返回结果，可以处理异常）
         *      FutureTask<Integer> futureTask = new FutureTask<>(new Callable01());
         *      new Thread(futureTask).start();
         *      // 阻塞等待整个线程执行完成，获取返回结果
         *      Integer integer = futureTask.get();
         *
         *      Future 可以获得异步结果
         * 4. 线程池[ExecutorService]
         *      给线程池直接提交任务.
         *      我们以后在业务代码里面，以上三种启动线程的方式都不用。【将所有的多线程异步任务都交给线程池执行】
         *      原生：service.execute(new Runable01());
         *      1、创建
         *          1）、Executors
         *          2）、new ThreadPoolExecutor()
         * 区别：
         *      1、2不能得到返回值，3可以获取返回值
         *      1、2、3都不能控制资源
         *      4 可以控制资源，系统性能稳定
         */

        /**
         *  七大参数：
         *  int corePoolSize    ：核心线程数[一直存在]
         *  int maximumPoolSize : 最大线程数量；控制资源
         *  long keepAliveTime  : 存活时间
         *  TimeUnit unit       : 时间单位
         *  BlockingQueue<Runnable> workQueue   : 阻塞队列
         *  ThreadFactory threadFactory         : 线程创建的工厂
         *  RejectedExecutionHandler handler    :如果队列满了，按照我们指定的拒绝策略，拒绝执行任务
         */
        ThreadPoolExecutor executor = new ThreadPoolExecutor(5,
                200,
                10,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(100000),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );

        // Executors.newCachedThreadPool()
        // Executors.newFixedThreadPool();
        // Executors.newScheduledThreadPool()
        // Executors.newSingleThreadExecutor()
    }

    public static class Thread01 extends Thread {
        @Override
        public void run() {
            System.out.println("当前线程: " + Thread.currentThread().getId());
            int i = 10/2;
            System.out.println("运行结果：" + i);
        }
    }

    public static class Runable01 implements Runnable {
        @Override
        public void run() {
            System.out.println("当前线程: " + Thread.currentThread().getId());
            int i = 10/2;
            System.out.println("运行结果：" + i);
        }
    }

    public static class Callable01 implements Callable<Integer> {

        @Override
        public Integer call() throws Exception {
            System.out.println("当前线程: " + Thread.currentThread().getId());
            int i = 10/2;
            System.out.println("运行结果：" + i);
            return i;
        }
    }


}
